package com.youlu.campus.starter.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

/**
 * @Description: FilterReConfiguration
 * @Date 2025/7/9
 * @module FilterReConfiguration
 * @author: su
 */
@Slf4j
@Configuration
@ServletComponentScan
public class WebFilterConfiguration {

    /**
     * 跨域处理 过滤器
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 允许的网站域名，全允许则设为 *
        // config.addAllowedOrigin("*");
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");// 允许 HEADER 或 METHOD ， * 为全部
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        // 这个顺序很重要，为避免麻烦请设置在最前
        bean.setOrder(0);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

    /**
     * 超时日志输出
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean timeFilter() {
        RequestTimeFilter timeFilter = new RequestTimeFilter();
        FilterRegistrationBean bean = new FilterRegistrationBean(timeFilter);
        bean.setOrder(1);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}
